import os
import time
import urllib3
import json
import shutil
import requests
import notify
import deploy_card
import cdn_refresh

def save_card_param(param):
    cwd = os.getcwd()
    with open(os.path.join(cwd, "card.json"), "w") as f:
        f.write(param)

def load_update_card():
    cwd = os.getcwd()
    card = os.path.join(cwd, "card.json")

    rindex = []
    tindex = []
    with open(card, "r") as fr:
        content = fr.read()
        strip = content.strip()
        lines = strip.split(",")
        
        # parse groups
        groupline = lines[0]
        if (len(groupline) > 0):
            if (groupline.find("-") > 0):
                rline = groupline.split("-")
                rstart = int(rline[0])
                rend = int(rline[1])

                for i in range(rstart, rend + 1):
                    rindex.append(i)
            else:
                rindex.append(int(groupline))
        print("groups:" + str(rindex))
        
        if len(lines) > 1:
            themeline = lines[1]
            if (len(themeline) > 0):
                if (themeline.find("-") > 0):
                    rline = themeline.split("-")
                    rstart = int(rline[0])
                    rend = int(rline[1])

                    for i in range(rstart, rend + 1):
                        tindex.append(i)
                else:
                    tindex.append(int(themeline))
            print("themes:" + str(tindex))
    return rindex, tindex


def sync_card_to_release(param, url_config, request_configs, context):
    save_card_param(param)

    cwd = os.getcwd()

    test = url_config["TEST"]
    testdir = os.path.join(cwd, "temp/" + test["local_dir"])
    print("temp dir " + testdir)
    if os.path.exists(testdir):
        shutil.rmtree(testdir)
    os.mkdir(testdir)

    config = {"CF_AndroidCardsConfig", "CF_iOSCardsConfig",}
    testconfigs = request_configs(test, testdir, "list", config)
    print("configs: " + str(testconfigs))

    groups, themes = load_update_card()

    if (len(groups) == 0 and len(themes) == 0):
        context["Status"]="deploy assets is null"
        notify.push_result(context)
        exit(0)

    sync_assets = []
    for key in testconfigs:
        print("=================================")
        print(key)

        with open(key, "rb") as freader:
            data = json.load(freader)

            platform = None
            if "Android" in key:
                platform = "Android"
            elif "iOS" in key:
                platform = "iOS"
            
            data_group = data["group"]
            data_card = data["cards"]
            for group in groups:
                item = data_group[str(group)]
                if item == None:
                    print("data.group not exist group:" + group)
                    context["Status"]="deploy group not exist"
                    notify.push_result(context)
                    exit(0)
                print(item["path"])
                sync_assets.append(platform + "/" + item["path"])

                rstart = group * 9 + 1
                rend = group * 9 + 9

                #  限时卡组
                if group >= 11111:
                    rstart = rstart + 1
                    rend = rend + 1
                for i in range(rstart, rend + 1):
                    item = data_card[str(i)]
                    if item == None:
                        print("data.card not exist card:" + group)
                        context["Status"]="deploy card not exist"
                        notify.push_result(context)
                        exit(0)
                    sync_assets.append(platform + "/" + item["path"])
            
            data_theme = data["theme"]
            for theme in themes:
                item = data_theme[str(theme)]
                if item == None:
                    print("data.theme not exist theme:" + theme)
                    context["Status"]="deploy theme not exist"
                    notify.push_result(context)
                    exit(0)
                sync_assets.append(platform + "/" + item["path"])

    print("sync assets:\n" + str(sync_assets))
    deploy_card.deploy(sync_assets, context)

    time.sleep(10)
    cdnurls = check_card_assets(sync_assets, url_config, context)

    # push cdn
    cdn_refresh.push(cdnurls)

def check_card_assets(sync_assets, url_config, context):
    print("check_card_assets:")
    print(sync_assets)

    cdnurls = []
    awscdn = url_config["AWSCDN"]
    aliyuncdn = url_config["AliyunCDN"]

    result = []
    for key in sync_assets:
        assetUrl = url_config["RELEASE"]["card_url"]  + "/" + key
        aliyunUrl = assetUrl.replace(awscdn, aliyuncdn)
        cdnurls.append(aliyunUrl)

        r = requests.get(aliyunUrl, stream=True)
        print(aliyunUrl + "  status_code:" + str(r.status_code))
        if r.status_code != 200:
            result.append(key)

    if len(result) > 0:
        print("check card fail:\n " + str(result))
        context["Status"] = "sync_card_assets Fail"
    else:
        print("check card success")
        context["Status"] = "sync_card_assets Success"
    notify.push_result(context)
    return cdnurls